import processing.core.PApplet;
import controlP5.ControlCanvas;
import controlP5.ControlGroup;


public class DrawObject extends ControlCanvas{
	PApplet theApplet;
	Canvas parent;
	ControlGroup group;
	float xPos, yPos;
	float width, height, circleRadius;
	boolean boundingBox;
	boolean isActive;
	int color;
	
	DrawObject(PApplet _theApplet, Canvas _parent, ControlGroup _group, float _xPos, float _yPos) {
		theApplet = _theApplet;
		parent = _parent;
		group  = _group;
		xPos = _xPos;
		yPos = _yPos;
		color = 128;
		isActive = false;
		
		
	}

	
	public void draw(PApplet _theApplet) {
		theApplet.fill(color);
		circleRadius = 25;
		
		//draws the object if it is not active
		if(!isActive)
			theApplet.ellipse(xPos,yPos,2*circleRadius,2*circleRadius);
		
		//if active, draws the object in the position of the mouse
		else
			theApplet.ellipse(theApplet.mouseX - group.absolutePosition().x - circleRadius,theApplet.mouseY - group.absolutePosition().y - circleRadius,2*circleRadius,2*circleRadius);		
	}
	
	public boolean handlePress( int mouseX, int mouseY) {
		if(!boundingBox)
			if(Main.dist(xPos, yPos, mouseX- group.absolutePosition().x - circleRadius, mouseY- group.absolutePosition().y - circleRadius) < circleRadius) {
				color = 200;
				isActive = true;
				Main.activeObject = this;
				return true;
			}
		return false;
	}
	public void handleRelease( int mouseX, int mouseY) {
		xPos = theApplet.mouseX - group.absolutePosition().x - circleRadius;
		yPos = theApplet.mouseY - group.absolutePosition().y  - circleRadius;
		isActive = false;
		Main.activeObject = null;
		System.out.println(xPos + " " + yPos+ " ");
		if((xPos > 0 && yPos > 0) && (xPos < parent.parent.width && yPos < parent.parent.height && parent.parent != Main.main)) 
			return;
		else {
			boolean eventHandled = false;
			for(MainGroup g: Main.groupList) {
				if(g != parent.parent && g.handleRelease(this, mouseX, mouseY)) {
					eventHandled = true;
					break;
				}
			}
			if(!eventHandled) {
				group.removeCanvas(this);
				switchGroup(Main.main);
				Main.main.theGroup.addCanvas(this);
			}
		}		
	}
	public void switchGroup( MainGroup g) {
		group = g.theGroup;
		parent.drawQueue.remove(this);
		parent = g.theCanvas;
		g.theCanvas.drawQueue.add(this);
		xPos = theApplet.mouseX - group.absolutePosition().x - circleRadius;
		yPos = theApplet.mouseY - group.absolutePosition().y  - circleRadius;
	}
}
